#include "Enemy.h"
#include "EnemyAI.h"


#define FRAME_ENEMY "enemy%d_%d.png"
#define BODY_ENEMY  "enemy%d"

Enemy::Enemy()
{
}

Enemy::~Enemy()
{

}

void Enemy::initGameObjectWith(GamePlayScreen *_gameScreen, CCDictionary *_dict, signed char _group)
{
    GameObject::initGameObjectWith(_gameScreen, _dict);

    group = _group;

    objType = ENEMY;
    charType = _dict->valueForKey(KEY_TYPE)->intValue();
    flyForce = CCPointMake(0.3f * ScreenManager::sharedScreenMan()->scaleFactor,
                           0.6f * ScreenManager::sharedScreenMan()->scaleFactor);

    this->createSprite();
    this->createPhysicBody();
    this->createBalloon();

    // create enemy control
    controlAI = EnemyAI::createEnemyAI((ENEMY_TYPE)charType, handler, this);
}

void Enemy::playEnemy(bool _play)
{
    this->isControllable = _play;
}

void Enemy::createSprite()
{    
    sprite = new CCSprite();
    sprite->initWithSpriteFrameName(CCString::createWithFormat(FRAME_ENEMY, charType, 0)->getCString());
    originPos = getPosFromDict(dataDict, sprite->getContentSize());
    sprite->setPosition(originPos);
    sprite->setTag(ENEMY);
}

void Enemy::createPhysicBody()
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;

    bodyDef.userData = this;
    if (sprite) {
        bodyDef.position.Set(sprite->getPositionX() / PTM_RATIO, sprite->getPositionY() / PTM_RATIO);
    }
    physicBody = handler->world->CreateBody(&bodyDef);

    DataAccess::sharedDataAccess()->getFixturesForBody(physicBody,
                                                       CCString::createWithFormat(BODY_ENEMY, charType)->getCString(), group);
}

void Enemy::beginContact(b2Fixture *ownFixture, b2Fixture *otherFixture, b2Contact *contact)
{
    Character::beginContact(ownFixture, otherFixture, contact);
}

void Enemy::endContact(b2Fixture *ownFixture, b2Fixture *otherFixture, b2Contact *contact)
{
    Character::endContact(ownFixture, otherFixture, contact);
}

void Enemy::update(float dt)
{
    Character::update(dt);
    controlAI->update(dt);
}
